package com.paradise.rsasign;

import com.alibaba.fastjson.JSON;
import com.paradise.rsasign.utils.RsaKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.TreeMap;

@RestController
@Slf4j
public class TestController {

    @GetMapping("/")
    public ResponseEntity<String> status() {
        return new ResponseEntity<>("Hello~", HttpStatus.OK);
    }

    @PostMapping("/callback")
    public ResponseEntity<String> getCallBack(@RequestBody CallBackData callBackData) {
        log.info("回调请求参数：{}", callBackData);

        // 返回签名值
        byte[] sign = Base64.decodeBase64(callBackData.getSign());
        // 验签
        TreeMap<String, Object> paramMap = new TreeMap<>();
        paramMap.put("id", callBackData.getId());
        paramMap.put("status", callBackData.getStatus());
        paramMap.put("timeStamp", callBackData.getTimeStamp());

        log.info("publicKey-> {}", PkConstant.PLATFORM_PUB_KEY);
        log.info("signString-> {}" ,JSON.toJSONString(paramMap));

        boolean verify = RsaKeyUtil.verify(JSON.toJSONString(paramMap),
                RsaKeyUtil.decryptBASE64(PkConstant.PLATFORM_PUB_KEY), sign);
        log.info("验签结果：{}", verify);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
